<?php
require_once APPLICATION_PATH . '/controllers/LoginController.php';

/**
 * 文件控制器
 * @author Administrator
 *
 */
class FileController extends  LoginController//Zend_Controller_Action
{
	public $mapping = array(
		"form_path" 		=> "path",
		"form_local_path" 	=> "local_path",
		"form_filename" 	=> "filename",
		"form_type" 		=> "type",
		"form_size" 		=> "size",
		"form_hash" 		=> "hash",
		"form_creat_time" 	=> "creat_time",
		"form_deleted" 		=> "deleted",
		"form_enabled" 		=> "enabled"
	);
    
	public function init()
    {
        /* Initialize action controller here */
    	parent::init();
    }

    public function indexAction()
    {
        //$confM = new Application_Model_DbTable_File();
        $confF = new Application_Form_File(); 
                
        $this->view->form = $confF;
    }
	
	public function listAction(){
    	if($this->getRequest()->ispost()){
    		$pageH = $this->_helper->Flexgp();
    		$userM = new Application_Model_DbTable_File();
    		$data = $userM->getFileListForFlex($userM);
    		$page = $data['page'];
			$total= $data['total'];
			$data = $data['data'];
			
			$data_arr = $this->view->jqflexgrid($data,$page,$total);
			$this->_helper->json($data_arr);
    	}
    }


    public function creatAction(){

    }
    
    public function editAction(){

    }
    
    public function delAction(){
        if($this->getRequest()->ispost()){
    		//ajax
    		if($this->getRequest()->isXmlHttpRequest()){
    			$reData = array(
    				"status" => 0,
    				"msg"	 => "失败。"
    			);
    			$ids = $this->getRequest()->getParam("ids",0);
    			    			
    			try{
    				$fileM = new Application_Model_DbTable_File();
    				$delRows = $fileM->delByIds($ids);
	    			$reData["status"] = 1;
	    			$reData["msg"] = "ok,删除了{$delRows}条数据！";
    			}catch (Exception $e){
    				$reData["msg"]="数据库操作失败!";
    			}
    		}
    		$this->_helper->json($reData);	
    	}
    }
    
    public function disableAction(){
        if($this->getRequest()->ispost()){
    		//ajax
    		if($this->getRequest()->isXmlHttpRequest()){
    			$reData = array(
    				"status" => 0,
    				"msg"	 => "失败。"
    			);
    			$ids = $this->getRequest()->getParam("ids",0);
    			    			
    			try{
    				$userM = new Application_Model_DbTable_File();
    				$delRows = $userM->disabByIds($ids);
	    			$reData["status"] = 1;
	    			$reData["msg"] = "ok,禁用了{$delRows}条数据！";
    			}catch (Exception $e){
    				$reData["msg"]="数据库操作失败!";
    			}
    		}
    		$this->_helper->json($reData);	
    	}
    }
    
    public function enableAction(){
        if($this->getRequest()->ispost()){
    		//ajax
    		if($this->getRequest()->isXmlHttpRequest()){
    			$reData = array(
    				"status" => 0,
    				"msg"	 => "失败。"
    			);
    			$ids = $this->getRequest()->getParam("ids",0);
    			    			
    			try{
    				$userM = new Application_Model_DbTable_File();
    				$delRows = $userM->enabByIds($ids);
	    			$reData["status"] = 1;
	    			$reData["msg"] = "ok,启用了{$delRows}条数据！";
    			}catch (Exception $e){
    				$reData["msg"]="数据库操作失败!";
    			}
    		}
    		$this->_helper->json($reData);	
    	}
    }
    
    /**
     * 根据hash获得文件信息
     * Enter description here ...
     */
    public function getfileAction(){
    	try {
    		$hash = $this->getRequest()->getParam("hash","");
    		$fileM = new Application_Model_DbTable_File();
    		$select = $fileM->select();
    		$select->where("`hash` = ?",$hash);
    		$data = $fileM->fetchRow($select);
    		
    		$reData = array(
    			"status" => 0
    		);
    		if($data){
    			$reData["status"]=1;
    		}
    		$this->_helper->json($reData);
    	}catch (Exception $e){
    		$this->_helper->json(
	    		array(
	    			"status" => 0
	    		)
    		);
    	}
    	
    }
    
    /*
     * 上传完成，
     */
    public function uploadcompleteAction() {
    	try {
    		
    		$cookie = $this->getRequest()->getParam("cookie");
    		if(!empty($cookie)){
    			session_id($cookie);
    		}
    		
    		$hash = $this->getRequest()->getParam("hash","");
    		$ftype = $this->getRequest()->getParam("ftype","");
    		$size = $this->getRequest()->getParam("size",0);
    		$local_path = $this->getRequest()->getParam("local_path","");

    		//file_put_contents( APPLICATION_PATH.'/../public/dbquery.sql', date('H:i:s Y-m-d',time()). "--" . print_r($local_path,TRUE) . "--\n", FILE_APPEND);
    		
    		$local_path = json_decode('"'.$local_path.'"');
    		$local_path = str_replace('"', '', $local_path);
    		$local_path = json_decode('"'.$local_path.'"');

    		//file_put_contents( APPLICATION_PATH.'/../public/dbquery.sql', date('H:i:s Y-m-d',time()). "-处理之后localpath-" . print_r($local_path,TRUE) . "--\n", FILE_APPEND);
			
    		$path_parts = pathinfo($local_path);
			$fname = $path_parts["basename"];
			if($local_path == $fname){
				$filearr = explode("\\", $local_path);
				$fname = array_pop($filearr);
			}

    		//file_put_contents(  APPLICATION_PATH.'/../public/dbquery.sql',  "-fname- $fname --\n" , FILE_APPEND);
    		    		
    		//获取系统ftp路径
    		$sysconfM = new Application_Model_DbTable_Conf();
    		$ftp_home = $sysconfM->ftp_root;
    		//file_put_contents( APPLICATION_PATH.'/../public/dbquery.sql', date('H:i:s Y-m-d',time()). "-sssftp_home-" . $ftp_home . "--\n" , FILE_APPEND);
    		    		
    		
    		//用户目标文件路径
    		$userHomeDir = $this->_user_info->home_dir;
    		//file_put_contents( APPLICATION_PATH.'/../public/dbquery.sql', date('H:i:s Y-m-d',time()). "-userHomeDir-" . $userHomeDir . "--\n" , FILE_APPEND);
    		    		
    		//目标文件路径
    		$ofile = $ftp_home . $userHomeDir . '/' . $hash . $ftype;
    		//file_put_contents( APPLICATION_PATH.'/../public/dbquery.sql', date('H:i:s Y-m-d',time()). "-源路径-" . $ofile . "--\n" , FILE_APPEND);
    		//移动目标文件
    		$targetDir = APPLICATION_PATH . "/../upload/" . $hash . $ftype;
    		//file_put_contents( APPLICATION_PATH.'/../public/dbquery.sql', date('H:i:s Y-m-d',time()). "-目标-" . $targetDir . "--\n" , FILE_APPEND);
    		
    		
    		//移动
    		if (copy($ofile, $targetDir)) {
			    unlink($ofile);
			}
    		
			//将local path 和用户id插入user->file表中
			//$userFileM = new applic
			
			//如果文件信息存在，不管，若不存在则插入文件信息表中。			
			
    		$fileM = new Application_Model_DbTable_File();
    		$data = array(
    			"path" => $targetDir,
				"local_path" => $local_path,
    			"user_id"	=> $this->_user_id,
				"filename" => $fname,
				"type" => $ftype,
				"size" => $size,
				"hash" => $hash,
    			"short"=> $this->shorturl($hash),
				"creat_time" => time()
    		);
			//file_put_contents( APPLICATION_PATH.'/../public/dbquery.sql', date('H:i:s Y-m-d',time()). "-data-" . print_r($data,true) . "--\n" , FILE_APPEND);

    		if($fileM->insert($data)){
    			$reData = array(
	    			"status" => 1
	    		);
    		}else{
    			$reData = array(
	    			"status" => 0
	    		);
    		};
    		$this->_helper->json($reData);
    		
    	}catch (Exception $e){
    		$this->_helper->json(
	    		array(
	    			"status" => 0
	    		)
    		);
    	}
    }
    
    /**
     * 上传控制器
     */
    public function uploadAction(){
    	$this->_helper->layout()->disableLayout();
    	
    	if (isset($_POST["PHPSESSID"])) {
			session_id($_POST["PHPSESSID"]);
		}
		
		//session_start();
		@ini_set("html_errors", "0");
	
		// Check the upload
		if (!isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) {
			echo "ERROR:上传失败";
			exit(0);
		}
	
		// Get the image and create a thumbnail
		/*
		$img = imagecreatefromjpeg($_FILES["Filedata"]["tmp_name"]);
		if (!$img) {
			echo "ERROR:不能创建文件句柄 ". $_FILES["Filedata"]["tmp_name"];
			exit(0);
		}
		
		$width = imageSX($img);
		$height = imageSY($img);
	
		if (!$width || !$height) {
			echo "ERROR:非法的高度或宽度";
			exit(0);
		}*/
    
		//哈希文件
		$file_id = md5_file($_FILES["Filedata"]["tmp_name"]);

		//文件信息
		$file_info = pathinfo($_FILES["Filedata"]['name']);
		$extension = $file_info["extension"];
		
		//文件写入目录
		$fdir = $this->_appconf->uploadPath;
		
		//文件写入
		$fpath = $fdir.$file_id.".".$extension;
		if(!file_exists($fpath)){
			
			if (move_uploaded_file($_FILES['Filedata']['tmp_name'], $fpath)) {
			} else {
			    echo "ERROR:最终文件写入失败!\n";exit(0);
			}
		}
	
		// Build the thumbnail
		/*
		$target_width = 100;
		$target_height = 100;
		$target_ratio = $target_width / $target_height;
	
		$img_ratio = $width / $height;
	
		if ($target_ratio > $img_ratio) {
			$new_height = $target_height;
			$new_width = $img_ratio * $target_height;
		} else {
			$new_height = $target_width / $img_ratio;
			$new_width = $target_width;
		}
	
		if ($new_height > $target_height) {
			$new_height = $target_height;
		}
		if ($new_width > $target_width) {
			$new_height = $target_width;
		}
	
		$new_img = ImageCreateTrueColor(100, 100);
		if (!@imagefilledrectangle($new_img, 0, 0, $target_width-1, $target_height-1, 0)) {	// Fill the image black
			echo "ERROR:不能创建缩略图文件";
			exit(0);
		}
	
		if (!@imagecopyresampled($new_img, $img, ($target_width-$new_width)/2, ($target_height-$new_height)/2, 0, 0, $new_width, $new_height, $width, $height)) {
			echo "ERROR:不能修改缩略图尺寸";
			exit(0);
		}
	
		if (!isset($_SESSION["file_info"])) {
			$_SESSION["file_info"] = array();
		}*/
	
		// Use a output buffering to load the image into a variable
		/*ob_start();
		imagejpeg($new_img);
		$imagevariable = ob_get_contents();
		ob_end_clean();
		
		$_SESSION["file_info"][$file_id] = $imagevariable;*/
	
		//echo "FILEID:" . $file_id;	// Return the file id to the script
		
		$reParams = array();
		$requestP = $this->getRequest()->getParams();
		foreach ($requestP as $k => $p){
			if (substr($k,0,2) == "ju"){
				$reParams[$k] = $p;
			}
		}
		$rsData = array(
			"FILEID" => $file_id.".".$extension,
			"MIME"	 => $_FILES['Filedata']['type'], //MIME is not sure exits
			"SIZE"	 => $_FILES['Filedata']['size'],
			"request" => $reParams
		);
		$this->_helper->json($rsData);
		die(0);	
    }
    
	/**
     * ckediter的上传控制器
     */
    public function ckedituploadAction(){
    	
    	//ck回调标识
    	$CKEditorFuncNum = $this->getRequest()->getParam("CKEditorFuncNum");
    	$isSaveFile = $this->getRequest()->getParam("issave",FALSE);
    	$msg = "";
    	$fileurl = "";
    	
    	$this->_helper->layout()->disableLayout();
	
    	switch (1){
    		case 1: 
				// Check the upload
				if (!isset($_FILES["upload"]) || !is_uploaded_file($_FILES["upload"]["tmp_name"]) || $_FILES["upload"]["error"] != 0) {
					$msg = "ERROR:上传失败";
					break;
				}
				if($_FILES["upload"]["size"] > 1024*1024*2){
					$msg = "您上传的文件过大！请将图像压缩到2M以内！";
					break;
				}
				$imageSize = getimagesize($_FILES["upload"]["tmp_name"]);
				if(empty($imageSize)){
					$msg = "您上传的不是合法的图像文件！";
					break;
				};
			
				//todo:这里没有重新渲染图像以阻止其中恶意代码。
				//哈希文件
				$file_id = md5_file($_FILES["upload"]["tmp_name"]);
		
				//文件信息
				$file_info = pathinfo($_FILES["upload"]['name']);
				$extension = $file_info["extension"];
				
				//文件写入目录
				$fdir = $this->_appconf->uploadPath;
				
				//文件写入
				if(!empty($isSaveFile)){
					$fpath = $fdir.$file_id.".".$extension;
					if(!file_exists($fpath)){
						
						if (move_uploaded_file($_FILES['upload']['tmp_name'], $fpath)) {
						} else {
						    $msg = "ERROR:最终文件写入失败!\n";
						    break;
						}
					}
	    			$fileurl = $file_id.".".$extension;
				}else{
					$fileurl = "data:{$_FILES['upload']['type']};base64,";
    				$fileurl .= base64_encode(file_get_contents($_FILES['upload']['tmp_name']));					
				}
								
				break;
				default:
					$msg = "未知错误！";
				break;
    	}
    	//$fileurl = "";
		$rsStr='<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$CKEditorFuncNum.', \''.$fileurl.'\', \''.$msg.'\');</script>';
		die($rsStr);	
    }
    
    /**
     * 显示或下载
     * 访问时，形如/file/public/uploads/xxxx.jpg/showname/你好中国.jpg
     */
    public function publicAction(){
    	$file = $this->getRequest()->getParam("uploads","");
    	$showName = $this->getRequest()->getParam("showname");
    	
    	$filePath = APPLICATION_PATH . "/../data/upload/" . $file;
    	if(file_exists($filePath)){    		 
		    header("Content-type: ".Application_Service_Filemime::getMime($filePath));
		 
		    if(!empty($showName)){
			    $ua = $_SERVER["HTTP_USER_AGENT"];
			    $encoded_filename = rawurlencode($showName);
			    if (preg_match("/MSIE/", $ua)) {
			     header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
			    } else if (preg_match("/Firefox/", $ua)) {
			     header("Content-Disposition: attachment; filename*=\"utf8''" . $showName . '"');
			    } else {
			     header('Content-Disposition: attachment; filename="' . $showName . '"');
			    }
		    }
		    header("Content-Length: ". filesize($filePath));
	    	readfile($filePath);
    	}else {
    		$this->getResponse()->setHttpResponseCode(404);
    		$this->getResponse()->sendResponse();
    	}
    	die();
    }
    
    public function downloadAction(){
    	$token = $this->getRequest()->getParam("token");
    	$token = split("-", $token);
    	$id = intval($token[0]);
    	$hash = $token[1];
    	
    	$fileM = new Application_Model_DbTable_File();
    	$select = $fileM->select();
    	$select->where("`id` = ?",$id);    	
    	$select->where("`hash` = ?",$hash);
    	$file = $fileM->fetchRow($select);
    	$filepath = $file->path;
    	$filename = $file->filename;
    	
    	if(file_exists($filepath)){
    		$data = array(
    			"down_times" => ($file->down_times) + 1,
    		);
    		$fileM->update($data, "`id` = $id");
    		Application_Service_Downloadfile::downloads($filepath,$filename);
    	}else {
    		$this->getResponse()->setHttpResponseCode(404);
    		$this->getResponse()->sendResponse();
    	}
    	die();
    }
    
    public function getdownurlAction(){
    	$id = $this->getRequest()->getParam("id");
    	$fileM = new Application_Model_DbTable_File();
    	$select = $fileM->select();
    	$select->where("id = ?",intval($id));
    	$select->where("enabled > 0");
    	$select->where("deleted = 0");
    	
    	$file = $fileM->fetchRow($select);
    	$data = array(
    		"status"	=> 0,
    		"msg"		=> "失败！"
    	);
    	if($file){
    		$data["msg"] = $file->id . "-" .$file->hash;
    		$data["status"] = 1;
    		$data["surl"] = $this->shorturl($file->hash);
    	}
    	$this->_helper->json($data);
    }
    
	function shorturl($input) {
      $base32 = array (
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
        'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
        'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
        'y', 'z', '0', '1', '2', '3', '4', '5'
        );
      
      $hex = md5($input);
      $hexLen = strlen($hex);
      $subHexLen = $hexLen / 8;
      $output = array();
      
      for ($i = 0; $i < $subHexLen; $i++) {
        $subHex = substr ($hex, $i * 8, 8);
        $int = 0x3FFFFFFF & (1 * ('0x'.$subHex));
        $out = '';
      
        for ($j = 0; $j < 6; $j++) {
          $val = 0x0000001F & $int;
          $out .= $base32[$val];
          $int = $int >> 5;
        }
      
        $output[] = $out;
      }
      
      return $output[0];
    }
    
    /**
     * 扫描文件
     * Enter description here ...
     */
    function scanvedioAction(){
    	$mDir = APPLICATION_PATH . "/../video";
    		if ($handle = opendir($mDir)) {			
			    /* 这是正确地遍历目录方法 */
			    while (false !== ($file = readdir($handle))) {
			    	$mDir = realpath($mDir);
			    	$fileDir = $mDir.'/'.$file; //文件路径 $file是文件名
			    	$hash = md5_file($fileDir); //文件hash
			    	$file_info = pathinfo($fileDir);
			    	$ftype =  ".".$file_info["extension"];
			    	$size = filesize($fileDir);
			    	if(is_file($fileDir)){
						try {
							//用户目标文件路径
				    		$userHomeDir = $this->_user_info->home_dir;
				    		    		
				    		//目标文件路径
				    		$ofile = $fileDir;
				    		
				    		//移动目标文件
				    		$targetDir = APPLICATION_PATH . "/../upload/" . $hash . $ftype;				    		
				    		
				    		//移动
				    		if(!file_exists($targetDir)){
					    		if (copy($ofile, $targetDir)) {
								    //unlink($ofile);
								}
				    		}
				    		
							//将local path 和用户id插入user->file表中
							//$userFileM = new applic
							
							//如果文件信息存在，不管，若不存在则插入文件信息表中。			
							
				    		$fileM = new Application_Model_DbTable_File();
				    		$data = array(
				    			"path" => $targetDir,
								"local_path" => "",
				    			"user_id"	=> $this->_user_id,
								"filename" => iconv("GBK", "UTF-8",$file),
								"type" => $ftype,
								"size" => $size,
								"hash" => $hash,
				    			"short"=> $this->shorturl($hash),
								"creat_time" => time()
				    		);
				    		echo $file," ------------------     http://www.xia8.us/?",$this->shorturl($hash),"<br>\n";
							//file_put_contents( APPLICATION_PATH.'/../public/dbquery.sql', date('H:i:s Y-m-d',time()). "-data-" . print_r($data,true) . "--\n" , FILE_APPEND);
							$select = $fileM->select();
    						$select->where("`hash` = ?",$hash);
				    		$rs = $fileM->fetchRow($select);
				    		if(empty($rs)){
					    		if($fileM->insert($data)){
					    			$reData = array(
						    			"status" => 1
						    		);
					    		}else{
					    			$reData = array(
						    			"status" => 0
						    		);
					    		};
				    		}
				    		//$this->_helper->json($reData);
				    		
				    	}catch (Exception $e){
				    		$this->_helper->json(
					    		array(
					    			"status" => 0
					    		)
				    		);
				    	}
			    	}
			    }
    		}
			closedir($handle);
			die();
    }
}

